package com.sctvcloud.dongqu.base;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.app.DialogFragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.util.ArrayMap;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.githang.statusbar.StatusBarCompat;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.dialog.AlertDialogFragment;
import com.ruihang.generalibrary.ui.util.FragmentDialogShowHelper;
import com.ruihang.generalibrary.utils.GeneraLifeObser;
import com.sctvcloud.dongqu.R;
import com.sctvcloud.dongqu.application.Constances;
import com.sctvcloud.dongqu.application.SiChuanFocusApplication;
import com.sctvcloud.dongqu.beans.IntegralAddBean;
import com.sctvcloud.dongqu.http.AbsNetCallBack;
import com.sctvcloud.dongqu.http.NetUtils;
import com.sctvcloud.dongqu.ui.activities.ChooseCityActivity;
import com.sctvcloud.dongqu.ui.activities.LoginActivity;
import com.sctvcloud.dongqu.utils.StatusBarUtil;
import com.sctvcloud.dongqu.utils.UserManager;

import org.xutils.x;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2017/6/15.
 */

public class BaseActivity extends AppCompatActivity {
    protected SiChuanFocusApplication mApplication;
    private ProgressDialog dialog;
    private boolean isThisImmersive = false;//状态栏是否使用沉浸式

    public static final String EX_ID = "ex_id";
    public static final String EX_TITLE = "ex_title";
    public static final String EX_TYPE = "ex_type";
    public static final String EX_DATA = "ex_data";
    public static final String EX_HTML = "ex_html";
    public static final String EX_URL = "ex_url";
    public static final String EX_JSON = "ex_json";
    public static final String EX_TYPE_NEWS = "ex_type_news";
    public static final String EX_NEWS_ITEM = "ex_news_item";
    public static final String EX_COLLECT_ITEM = "ex_collect_item";
    public static final String EX_COMMENT_TYPE = "ex_comment_type";
    public static final String EX_COLUMN_TYPE = "ex_column_type";//栏目类型
    public static final String DO_UP_POS = "do_up_pos";
    protected static final int CODE_REQUEST_LOGIN = 303;

    public static String TAG_PERMISSION = "tag_permission";

    protected FragmentDialogShowHelper fragmentDialogShowHelper;

    protected boolean isThisShowing;

    protected int userExpiredCode;

    protected AlertDialogFragment permissionDialog;

    protected int loginMode;

    protected Unbinder mBaseUnbinder;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        isThisShowing = false;
        TAG_PERMISSION = TAG_PERMISSION + Integer.toHexString(hashCode());
        super.onCreate(savedInstanceState);
        GeneraLifeObser.changeLifeState(this, GeneraLifeObser.STATE_CREATED);
        this.mApplication = (SiChuanFocusApplication) getApplication();
        if (isThisImmersive) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//禁止横屏
            requestWindowFeature(Window.FEATURE_NO_TITLE);
        }
        initInject();
        if (isThisImmersive) {
            //沉浸式代码配置
            //当FitsSystemWindows设置 true 时，会在屏幕最上方预留出状态栏高度的 padding
            StatusBarUtil.setRootViewFitsSystemWindows(this, true);
            //设置状态栏透明
            StatusBarUtil.setTranslucentStatus(this);


            StatusBarUtil.setRootViewFitsSystemWindows(this, false);
        } else {
            StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.white));
        }
        //一般的手机的状态栏文字和图标都是白色的, 可如果你的应用也是纯白色的, 或导致状态栏文字看不清
        //所以如果你是这种情况,请使用以下代码, 设置状态使用深色文字图标风格, 否则你可以选择性注释掉这个if内容
        if (!StatusBarUtil.setStatusBarDarkTheme(this, true)) {
            //如果不支持设置深色风格 为了兼容总不能让状态栏白白的看不清, 于是设置一个状态栏颜色为半透明,
            //这样半透明+白=灰, 状态栏的文字能看得清
            StatusBarUtil.setStatusBarColor(this, 0x55000000);
        }
        fragmentDialogShowHelper = new FragmentDialogShowHelper();

    }

    @Override
    public void onStart() {
        super.onStart();
        GeneraLifeObser.changeLifeState(this, GeneraLifeObser.STATE_START);
    }

    @Override
    protected void onResume() {
        super.onResume();
        GeneraLifeObser.changeLifeState(this, GeneraLifeObser.STATE_RESUME);
        isThisShowing = true;
        UserManager.setActiveAC(this);
//        JLog.e("" + this);
    }

    @Override
    protected void onResumeFragments() {
        super.onResumeFragments();
        if (fragmentDialogShowHelper != null) {
            fragmentDialogShowHelper.onResume(getSupportFragmentManager());
        }
    }

    @Override
    protected void onPause() {
        isThisShowing = false;
        if (fragmentDialogShowHelper != null) {
            fragmentDialogShowHelper.onPause();
        }
        GeneraLifeObser.changeLifeState(this, GeneraLifeObser.STATE_PAUSE);
        super.onPause();
    }


    @Override
    public void onStop() {
        GeneraLifeObser.changeLifeState(this, GeneraLifeObser.STATE_STOP);
        super.onStop();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_REQUEST_LOGIN) {
            if (resultCode == LoginActivity.RESULT_OK) {
                onLoginSuc();
                userExpiredCode = 0;
            } else {
                onLoginUnSuc();
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (fragmentDialogShowHelper != null) {
            fragmentDialogShowHelper.onDestory();
            fragmentDialogShowHelper = null;
        }
        if (mBaseUnbinder != null) {
            mBaseUnbinder.unbind();
        }
        GeneraLifeObser.changeLifeState(this, GeneraLifeObser.STATE_DESTORY);
        GeneraLifeObser.removeLife(this);
        super.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        if (fragmentDialogShowHelper != null) {
            fragmentDialogShowHelper.onSaveStation();
        }
        super.onSaveInstanceState(outState);
    }

    protected void initInject() {
        x.view().inject(this);
    }

    protected void initButterknifeBiner(int layoutRes) {
        setContentView(layoutRes);
        mBaseUnbinder = ButterKnife.bind(this);
    }

    public boolean isThisShowing() {
        return isThisShowing;
    }

    public String getOwnerName() {
        return this + "";
    }

    public void onUserExpired(int code) {
        if (this.userExpiredCode != code) {
            this.userExpiredCode = code;
            onUserExpired();
            toast(R.string.login_expired_please_relogin);
        }
    }

    protected void onLoginUnSuc() {
    }

    protected void onLoginSuc() {
    }

    protected void onUserExpired() {
    }

    public boolean isThisImmersive() {
        return isThisImmersive;
    }

    public void setThisImmersive(boolean thisImmersive) {
        isThisImmersive = thisImmersive;
    }

    protected void toLogin() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivityForResult(intent, CODE_REQUEST_LOGIN);
    }

    public void safeShowDialog(@NonNull DialogFragment fragment, @NonNull String tag) {
//        if (fragmentDialogShowHelper != null && fragment.isAdded()) {
//            fragmentDialogShowHelper.showDialog(getSupportFragmentManager(), fragment, tag);
//        } else {
//
//            fragment.show(getSupportFragmentManager(), tag);
//        }

        if (!fragment.isAdded()) {
            fragmentDialogShowHelper.showDialog(getSupportFragmentManager(), fragment, tag);
        }
    }

    /**
     * @param content
     * @param isHoleMsg 是否是全部的msg, 若为true,则不拼接
     */
    protected void showPermissionDialog(String content, boolean isHoleMsg, int mode) {
        if (permissionDialog == null) {
            permissionDialog = new AlertDialogFragment().setLayoutRes(R.layout.fragment_alert_dialog_new);
            permissionDialog.setOnViewInit(new AlertDialogFragment.OnViewInit() {
                @Override
                public void onViewInit(Dialog dialog, Bundle savedInstanceState) {
                    permissionDialog.getOkView().setTextColor(ContextCompat.getColor(BaseActivity.this, R.color.colorRedMain));
                }
            });
            permissionDialog.setOnViewClick(new AlertDialogFragment.OnViewClick() {
                @Override
                public boolean onViewClick(View view, int viewItem, int mode) {
                    return onPermissionDialogViewClick(view, viewItem, mode);
                }
            });
        }
        permissionDialog.setModeTag(mode);
        permissionDialog.setMsgStr(isHoleMsg ? content : getString(R.string.need_permission) + content);
        permissionDialog.show(getSupportFragmentManager(), TAG_PERMISSION);
    }

    protected boolean onPermissionDialogViewClick(View view, int viewItem, int mode) {
        if (viewItem == AlertDialogFragment.VIEW_ITEM_OK) {
//            if (mode==)
//            PermissionUtils.toSetting(this,);
        }
        return true;
    }

    protected void showProgress(String msg, boolean cancelable) {
        if (dialog == null) {
            dialog = new ProgressDialog(this);
        }
        if (msg == null) {
            msg = "";
        }
        dialog.setMessage(msg);
        dialog.setCancelable(cancelable);
        if (!dialog.isShowing() && !this.isFinishing() && !this.isDestroyed()) {
            dialog.show();
        }
    }

    protected void showProgress(String msg) {
        showProgress(msg, true);
    }

    protected void closeProgress() {
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
    }

    public void toast(String str) {
        if (TextUtils.isEmpty(str)) {
            return;
        }
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }

    public void toastLong(String str) {
        if (TextUtils.isEmpty(str)) {
            return;
        }
        Toast.makeText(this, str, Toast.LENGTH_LONG).show();
    }

    public void toast(@StringRes int strRes) {
        Toast.makeText(this, strRes, Toast.LENGTH_SHORT).show();
    }

    public void toastLong(@StringRes int strRes) {
        Toast.makeText(this, strRes, Toast.LENGTH_LONG).show();
    }

    public void toastInCenter(String str) {
        Toast toast = Toast.makeText(this, str, Toast.LENGTH_SHORT);
        View view = toast.getView();
        if (view != null) {
//            TextView tv = (TextView) view.findViewById(com.android.internal.R.id.message);
            TextView tv = (TextView) view.findViewById(Resources.getSystem().getIdentifier("message", "id", "android"));
            if (tv != null) {
                tv.setTextColor(Color.WHITE);
                tv.setTextSize(15);
            }
            view.setBackgroundResource(R.drawable.bg_corners_black_toast);
        }
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    public int onOtherCallback(Message msg) {
        return 0;
    }

    /**
     * 增加积分
     * 1:签到;2:评论;3:转发;4:投稿;5:采用投稿;6:邀请码分享;7:新用户注册;8:输入邀请码
     *
     * @param type
     */
    protected void addInvitation(int type, final boolean isFinishView) {
        if(null!=UserManager.getInstance().getUser()) {
            ArrayMap<String, Object> p = new ArrayMap<>();
            p.put("ruleType", type);
            p.put("userId", UserManager.getInstance().getUser().getPhoneNumber());
            p.put("token", UserManager.getInstance().getUser().getToken());
            NetUtils.getNetAdapter().postAddIntegral(getOwnerName(), p, new AbsNetCallBack<IntegralAddBean>(IntegralAddBean.class) {
                @Override
                public void onSuc(IntegralAddBean result) {
                    String addMsg = "";
                    switch (result.getRuleType()){
                        case Constances.ADD_INTEGRAL_SIGN_IN :
                            addMsg = " 签到成功，奖励"+ result.getIntegral() + "积分~";
                            break;
                        case Constances.ADD_INTEGRAL_COMMENT:
                            addMsg = " 评论成功，奖励"+ result.getIntegral() + "积分~";
                            break;
                        case Constances.ADD_INTEGRAL_FORWARD:
                            addMsg = " 转发成功，奖励"+ result.getIntegral() + "积分~";
                            break;
                        case Constances.ADD_INTEGRAL_SUBMISSION:
                            addMsg = " 投稿成功，奖励"+ result.getIntegral() + "积分~";
                            break;
                        case Constances.ADD_INTEGRAL_USE_SUBMISSION:
                            addMsg = " 投稿被采用，奖励"+ result.getIntegral() + "积分~";
                            break;
                        case Constances.ADD_INTEGRAL_SHARE_INVITATION:
                            addMsg = " 分享邀请码成功，奖励"+ result.getIntegral() + "积分~";
                            break;
                        case Constances.ADD_INTEGRAL_REGISTER:
                            addMsg = " 注册成功，奖励"+ result.getIntegral() + "积分~";
                            break;
                        case Constances.ADD_INTEGRAL_INPUT_INVITATION:
                            addMsg = " 提交邀请码成功，奖励"+ result.getIntegral() + "积分~";
                            break;
                        case Constances.ADD_INTEGRAL_READ_NEWS:
                            addMsg = " 阅读新闻，奖励" + result.getIntegral() + "积分~";
                            break;
                        case Constances.ADD_INTEGRAL_DOUP:
                            addMsg = " 点赞成功，奖励" + result.getIntegral() + "积分~";
                            break;
                    }
                    if(!TextUtils.isEmpty(addMsg)) {
                        toastInCenter(addMsg);
                    }
                    if (isFinishView) {
                        finish();
                    }
                }

                @Override
                public void onEnd() {
                    super.onEnd();

                }

                @Override
                public void onError(Throwable ex, String errorMsg) {
                    super.onError(ex, errorMsg);
                }
            });
        }
    }
}
